package com.kuaidian.controller;

import java.io.File;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.kuaidian.model.api.ResponseMsg;
import com.kuaidian.pojo.TPhoto;
import com.kuaidian.service.PhotoService;
import com.kuaidian.util.AuthInterceptor;
import com.kuaidian.util.JacksonMgr;
import com.kuaidian.util.constant.Constant;
import com.kuaidian.util.constant.ErrorCode;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;


@Api(value="Common",description="fileupload")
@Controller
@RequestMapping( "/api/fileupload" )
public class FileController {

	@Autowired
	PhotoService photoService;
	
    private static Logger logger = Logger.getLogger(FileController.class);  
    
    @InitBinder     /* Converts empty strings into null when a form is submitted */
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
    
    
    @ApiOperation(value = "文件上传")
    @RequestMapping(value = "fileUpload",produces="application/json;charset=utf-8", method = RequestMethod.POST)  
    public @ResponseBody String fileUpload(HttpServletRequest request)   {  
    		int max_file_size = 1024*1024*10; //10M
	    	try {
	 	        // 设置上下方文  
		        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(  
		                request.getSession().getServletContext());  

		        // 检查form是否有enctype="multipart/form-data"  
		        if (multipartResolver.isMultipart(request)) {  
		            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
		      	  
		            String user_id = request.getParameter("user_id");
		            Iterator<String> iter = multiRequest.getFileNames();  
		            while (iter.hasNext()) {  
		                // 由CommonsMultipartFile继承而来,拥有上面的方法.  
		                MultipartFile file = multiRequest.getFile(iter.next());  
		            
		                if (file != null) {  
		       			 	
		                	if (file.getSize() > max_file_size) {
		    		 			ResponseMsg retMsg =   new ResponseMsg("文件不能大于"+max_file_size/1024+"KB",ErrorCode.ERROR,null);
		    					String retjsonString = JacksonMgr.toJSON(retMsg);
		    					return retjsonString;		
							}else{
								String originalFilename = file.getOriginalFilename();
								String fileName = "";
								if(originalFilename.indexOf(".gif") > -1){
									fileName = user_id + "_" + System.currentTimeMillis() + ".gif";  
								}else{
									fileName = user_id + "_" + System.currentTimeMillis() + ".png";
								}
			                	File localFile = new File(Constant.FILE_UPLOAD_PATH + fileName);  
			                    File parent = localFile.getParentFile(); 
			                    if(parent!=null&&!parent.exists()){ 
			                    	parent.mkdirs(); 
			                    } 
			                    file.transferTo(localFile);  
			                    
			                    
			                    TPhoto photo = new TPhoto();
			                    photo.setUrl(fileName);
			                    photo.setUser_id(new Integer(user_id));
			                    photo.setCreate_time(new Date());
			                    photoService.insertPhoto(photo);
			                    
			        			ResponseMsg retMsg =   new ResponseMsg("Ok",ErrorCode.OK,fileName);
			        			String retjsonString = JacksonMgr.toJSON(retMsg);
			        			return retjsonString;	
							}
		            		                    
		                }  
		  
		            }  
		        }  
		        
	 			ResponseMsg retMsg =   new ResponseMsg("上传失败",ErrorCode.ERROR,null);
				String retjsonString = JacksonMgr.toJSON(retMsg);
				return retjsonString;		
		        
			} catch (Exception e) {
				logger.error(e);
				return JacksonMgr.makeExceptionJSON(e);
			}
  } 

 	 
}
